//
//  MasterViewTableCell.m
//  PrintFamily
//
//  Created by edaihua on 16/2/26.
//  Copyright © 2016年 ___PrintFactory___. All rights reserved.
//

#import "PhotoListTableViewCell.h"
#import "PFPhoto.h"
#import "PFPhotosManager.h"
#import "UIImage+Crop.h"

@interface PhotoListTableViewCell()

@property (strong, nonatomic) PFPhoto     *photo;

@property (strong, nonatomic) UILabel     *photoNumberLabel;
@property (strong, nonatomic) UIView      *photoFrameView;

@property (strong, nonatomic) UIButton    *upButton;
@property (strong, nonatomic) UIButton    *downButton;

@property (nonatomic) PhotoPrintType cellType;

@end
@import Photos;
@implementation PhotoListTableViewCell

@synthesize photoFrameView;

const NSUInteger photoSelectBarHeight = 46.0;
const NSUInteger photoSelectBarToBottom = 30.0;

const NSInteger photoSelectBarTag = 100;
const NSInteger photoFrameViewTag = 101;

- (void)initWithPhoto:(PFPhoto*)photo delegate:(id)delegate andPrintType:(PhotoPrintType)type {
    self.photo = photo;
    self.delegate = delegate;
    [self preparePhotoFrameWithPrintType:type];
    [self showSquareImageForAsset:photo.asset];
    //[self preparePhotoWithAsset:photo.asset];
    [self preparePhotoSelectBar];
}

- (void)showSquareImageForAsset:(PHAsset *)asset
{
    CGSize targetPhotoSize = [self.photo.rectManager getPhotoSize];
    CGRect cropPixelRect   = [self.photo.rectManager getCropRect];
    
    NSInteger retinaScale = [UIScreen mainScreen].scale;
    //CGSize retinaSquare = CGSizeMake(100*retinaScale, 100*retinaScale);
    CGSize retinaSquare = CGSizeMake(targetPhotoSize.width*retinaScale, targetPhotoSize.height*retinaScale);
    
    
    PHImageRequestOptions *cropToSquare = [[PHImageRequestOptions alloc] init];
    cropToSquare.resizeMode = PHImageRequestOptionsResizeModeExact;
    
    //CGFloat cropSideLength = MIN(asset.pixelWidth, asset.pixelHeight);
    //CGRect square = CGRectMake(100, 0, cropSideLength, cropSideLength);
    CGRect cropRect = CGRectApplyAffineTransform(cropPixelRect,
                                                 CGAffineTransformMakeScale(1.0 / asset.pixelWidth,
                                                                            1.0 / asset.pixelHeight));
    
    NSLog(@"Crop rect: x:%f, y:%f, w:%f, h:%f", cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
    
    cropToSquare.normalizedCropRect = cropRect;
    
    void (^resultHandler)(UIImage*, NSDictionary*) = ^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        if (!result) {
            return;
        }
        PFPhotoRectManager *photoRectManager = self.photo.rectManager;
        CGSize              photoSize        = [photoRectManager getPhotoSize];
        UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake([photoRectManager getPhotoOriginX], [photoRectManager getPhotoOriginY], photoSize.width, photoSize.height)];
        [imgView setImage:result];
        [imgView setContentMode:UIViewContentModeScaleAspectFit];
        
        for (UIView *view in [self.photoFrameView subviews]) {
            if ([view isKindOfClass:[UIImageView class]]) {
                [view removeFromSuperview];
            }
        }
        
        [self.photoFrameView addSubview:imgView];
        
        UIView *view = [self.photoFrameView viewWithTag:photoSelectBarTag];
        if (view) {
            [self.photoFrameView bringSubviewToFront:view];
        }
        
    };
    
    [[PHImageManager defaultManager] requestImageForAsset:(PHAsset *)asset
                                               targetSize:retinaSquare
                                              contentMode:PHImageContentModeAspectFit
                                                  options:cropToSquare
                                            resultHandler:resultHandler];
}

//#define DEBUG_PHIMAGEMANAGER
- (void)preparePhotoWithAsset:(PHAsset*)asset  {
    
    void (^resultHandler)(UIImage*, NSDictionary*) = ^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        if (!result) {
            return;
        }
        
        UIImage            *resultImage      = result;
        PFPhotoRectManager *photoRectManager = self.photo.rectManager;
        
        NSLog(@"photo size: w:%f, h:%f", result.size.width, result.size.height);
#ifdef DEBUG_PHIMAGEMANAGER
        photoRectManager.imagePixelSize = resultImage.size;
        CGSize photoSize = [photoRectManager getPhotoSize];
        UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake([photoRectManager getPhotoOriginX], [photoRectManager getPhotoOriginY], photoSize.width, photoSize.height)];
#else
        BOOL isLandscape = result.size.width > result.size.height;
        if (isLandscape) {
            // Need to rotate the image to fit the portrait screen
            resultImage = [UIImage imageWithCGImage:result.CGImage scale:result.scale orientation:UIImageOrientationRight];
        }
        
        resultImage = [UIImage fixrotation:resultImage];
        
        [photoRectManager updatePixelSize:resultImage.size];
        
        resultImage = [resultImage cropImageWithRect:[photoRectManager getCropRect]];
        CGSize photoSize = [photoRectManager getPhotoSize];
        
        UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake([photoRectManager getPhotoOriginX], [photoRectManager getPhotoOriginY], photoSize.width, photoSize.height)];
#endif 
        
        [imgView setImage:resultImage];
        [imgView setContentMode:UIViewContentModeScaleAspectFit];
        
        for (UIView *view in [self.photoFrameView subviews]) {
            if ([view isKindOfClass:[UIImageView class]]) {
                [view removeFromSuperview];
            }
        }
        
        [self.photoFrameView addSubview:imgView];
        
        UIView *view = [self.photoFrameView viewWithTag:photoSelectBarTag];
        if (view) {
            [self.photoFrameView bringSubviewToFront:view];
        }
    };

    PHImageRequestOptions* requestOption = [[PHImageRequestOptions alloc] init];

#ifdef DEBUG_PHIMAGEMANAGER
    //requestOption.normalizedCropRect = CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
    
    requestOption.synchronous = YES;
    requestOption.resizeMode = PHImageRequestOptionsResizeModeExact;
    //requestOption.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    //requestOption.networkAccessAllowed = NO;
    //CGFloat cropSizeLength = MIN(asset.pixelWidth, asset.pixelHeight);
    CGRect cropRect = CGRectMake(0, 0, asset.pixelWidth, asset.pixelWidth);
    
    requestOption.normalizedCropRect = CGRectApplyAffineTransform(cropRect, CGAffineTransformMakeScale(1 / asset.pixelWidth, 1.0 / asset.pixelHeight));
    
    NSLog(@"photo pixel Size:w:%lu, h:%lu", asset.pixelWidth, asset.pixelHeight);
#else
    requestOption.synchronous = NO;
    requestOption.resizeMode = PHImageRequestOptionsResizeModeFast;
    requestOption.networkAccessAllowed = NO;
#endif
    
    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:PHImageManagerMaximumSize
                                               //targetSize:PHImageManagerMaximumSize//CGSizeMake(200, 200)
                                              contentMode:PHImageContentModeAspectFit
                                                  options:requestOption
                                            resultHandler:resultHandler];
}

- (void)preparePhotoFrameWithPrintType:(PhotoPrintType)type {
    
    if ([self.contentView viewWithTag:photoFrameViewTag] == nil || self.cellType != type) {
        
        UIView *oldFrameView = [self.contentView viewWithTag:photoFrameViewTag];
        [oldFrameView removeFromSuperview];
        
        PFPhotoRectManager *rectManager = self.photo.rectManager;
        if (rectManager) {
            PFCommonRectManager *commonRectManager = rectManager.commonRectManager;
            
            self.photoFrameView = [[UIView alloc] initWithFrame:CGRectMake([commonRectManager getPhotoFrameOriginXInMasterCell], [commonRectManager getPhotoFrameOriginYInMasterCell], commonRectManager.frameSize.width, commonRectManager.frameSize.height)];
            self.photoFrameView.backgroundColor = [UIColor whiteColor];
            self.photoFrameView.tag = photoFrameViewTag;
        }
        self.cellType = type;
        
        [self.contentView addSubview:self.photoFrameView];
    }
}

- (void)preparePhotoSelectBar {
    if ([self.photoFrameView viewWithTag:photoSelectBarTag] == nil) {
        CGRect frame;
        CGSize photoFrameSize = self.photoFrameView.frame.size;
        const CGFloat barHeight = 46.0;
        
        frame.size.width = 188.0;
        frame.size.height = barHeight;
        frame.origin.x = photoFrameSize.width/2 - frame.size.width/2;
        frame.origin.y = photoFrameSize.height - photoSelectBarToBottom - frame.size.height;
        
        UIView *photoSelectorView = [[UIView alloc] initWithFrame:frame];
        photoSelectorView.backgroundColor = UIColorBlue;
        photoSelectorView.alpha = 1;
        photoSelectorView.tag = photoSelectBarTag;
        [self.photoFrameView addSubview:photoSelectorView];
        
        self.downButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, barHeight, barHeight)];
        [self.downButton setImage:[UIImage imageNamed:@"down_arrow"] forState:UIControlStateNormal];
        [photoSelectorView addSubview:self.downButton];
        
        self.upButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width - frame.size.height - 10.0, 0.0, barHeight, barHeight)];
        [self.upButton setImage:[UIImage imageNamed:@"up_arrow"] forState:UIControlStateNormal];
        [photoSelectorView addSubview:self.upButton];
        
        if ([self.delegate isKindOfClass:[UITableViewController class]]) {
            if ([self.delegate respondsToSelector:@selector(tapUpButton:)]) {
                [self.upButton addTarget:self.delegate action:@selector(tapUpButton:) forControlEvents:UIControlEventTouchUpInside];
            }
            
            if ([self.delegate respondsToSelector:@selector(tapDownButton:)]) {
                [self.downButton addTarget:self.delegate action:@selector(tapDownButton:) forControlEvents:UIControlEventTouchUpInside];
            }
        }
        
        const CGFloat labelWidth = 50.0;
        self.photoNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(frame.size.width/2 - labelWidth/2, 0.0, labelWidth, barHeight)];
        self.photoNumberLabel.text = [NSString stringWithFormat:@"x %lu", (unsigned long)self.photo.printNumber];
        self.photoNumberLabel.textAlignment = NSTextAlignmentCenter;
        self.photoNumberLabel.textColor = [UIColor whiteColor];
        [photoSelectorView addSubview:self.photoNumberLabel];
        
        [self.photoFrameView bringSubviewToFront:photoSelectorView];
    }
}

- (void)increasePhotoNumber {
    if ([self.photo increasePrintNumber])
    {
        self.downButton.hidden = NO;
    }
    
    self.photoNumberLabel.text = [NSString stringWithFormat:@"x %lu", (unsigned long)self.photo.printNumber];
}

- (void)decreasePhotoNumber {
    if ([self.photo decreasePrintNumber] == 0) {
        self.downButton.hidden = YES;
    }
    self.photoNumberLabel.text = [NSString stringWithFormat:@"x %lu", (unsigned long)self.photo.printNumber];
}

#pragma mark - synthethizer
- (UIView*)photoFrameView {
    if (photoFrameView == nil) {
        
        PFPhotoRectManager *rectManager = self.photo.rectManager;
        if (rectManager) {
            PFCommonRectManager *commonRectManager = rectManager.commonRectManager;
            
            photoFrameView = [[UIView alloc] initWithFrame:CGRectMake([commonRectManager getPhotoFrameOriginXInMasterCell], [commonRectManager getPhotoFrameOriginYInMasterCell], commonRectManager.frameSize.width, commonRectManager.frameSize.height)];
            photoFrameView.backgroundColor = [UIColor whiteColor];
            photoFrameView.tag = photoFrameViewTag;
        }
    }
    return photoFrameView;
}

@end
